package com.zcb.agrimarket.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcb.agrimarket.constant.JwtClaimsConstant;
import com.zcb.agrimarket.context.BaseContext;
import com.zcb.agrimarket.pojo.User;
import com.zcb.agrimarket.pojo.UserContext;
import com.zcb.agrimarket.properties.JwtProperties;
import com.zcb.agrimarket.result.Result;
import com.zcb.agrimarket.service.UserService;
import com.zcb.agrimarket.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zcb
 * @since 2024-04-03
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理相关接口")
@Slf4j
@CrossOrigin//$$$用于处理跨域问题
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping
    @ApiOperation("新增用户")
    public Result save(@RequestBody User user){
        userService.save(user);
        return Result.success("成功添加用户");
    }

    @PostMapping("/delete")
    @ApiOperation("删除用户")
    public Result<String> deleteByIds(@RequestParam Long id){
        log.info("准备删除用户的ID：{}",id);
        userService.deleteByMyid(id);
        return Result.success("成功删除用户");
    }

    @PutMapping
    @ApiOperation("修改用户信息")
    public Result<String> updata(@RequestBody User user){
        userService.updateById(user);
        return  Result.success("成功修改用户信息！");
    }

    @GetMapping("/{id}")
    @ApiOperation("单个查询用户信息")
    public Result<User> getbyid(@PathVariable Long id){
        log.info("将要查询的用户ID：{}",id);
        User user = userService.getById(id);
        return Result.success(user);
    }

    @GetMapping("/myId")
    @ApiOperation("查询本人信息")
    public Result<User> getbyMyId(){
        long id = BaseContext.getCurrentId();
        log.info("将要查询的用户ID：{}",id);
        User user = userService.getById(id);
        return Result.success(user);
    }

    @GetMapping()
    @ApiOperation("分页查询用户")
    public Result<Page> getAll(Integer page, Integer pageSize, String username){
        log.info("当前页码：{}",page);
        log.info("页面大小：{}",pageSize);
        log.info("查询条件：{}",username);
        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(username),User::getUsername,username);

        //执行查询
        userService.page(pageInfo,queryWrapper);

        return Result.success(pageInfo);
    }

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserContext> login(@RequestParam String account, String password){
        log.info("用户的账号密码为：{},{}",account,password);
        User user = userService.getByaccount(account,password);

        //准备放在JWT令牌中的信息
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID, user.getId());
        log.info("准备保存的用户id:{}",user.getId());
        //调用接口生成JWT令牌
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        log.info("生成的JWT值：{}",token);

        UserContext userContext = new UserContext();
        userContext.setToken(token);
        userContext.setRole(user.getRole());

        return Result.success(userContext);
    }

    @PostMapping("/getCode")
    @ApiOperation("接收验证码")
    public Result<String> getCode(String account,String mailbox){
        log.info("用户账号为：{}，用户邮箱为：{}",account,mailbox);
        if(mailbox==null){
            return Result.error("邮箱为空！");
        }
        User user = userService.getBymailbox(account,mailbox);
        if(mailbox==null){
            return Result.error("邮箱不是该账号绑定的邮箱！");
        }
        userService.getCode(mailbox);
        return Result.success("已发送验证邮件！");
    }

    @PostMapping("/updatePassword")
    @ApiOperation("修改密码")
    public Result<String> updatePassword(String account,String password,String mailbox,String verifyCode){
        log.info("用户账号为：{}，用户想要重新设置的密码：{}，用户邮箱:{}，用户收到的验证码为：{}",account,password,mailbox,verifyCode);
        if(userService.updatePassword(account,password,mailbox,verifyCode)==true) return Result.success("成功修改密码！");
        else return Result.error("验证码错误，请重新获取验证码并修改！");
    }

}

